<template>
  <div class="params">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
        </el-col>
      </el-row>
      <el-form label-width="130px">
        <el-form-item label="选择商品分类：">
          <el-cascader
            expand-trigger="hover"
            :options="GoodsCateList"
            v-model="cateId"
            :props="cateProps"
            @change="handleParamsChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!--
        label  选项卡标题  看见的文本（切换的文本）
        v-model  绑定值，选中选项卡的 name
      -->
      <el-tabs v-model="activeName" @tab-click="handleTabChange">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <el-table :data="manyList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primay"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  @close="removeTag(scope.row,index)"
                >{{item}}</el-tag>
                <el-input
                  class="tag_input"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="$event.target.blur"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editSearch(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <el-table :data="onlyList" border stripe>
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editSearch(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加 -->
    <el-dialog
      :title="'添加'+activeTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addClose"
    >
      <el-form label-width="100px" :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item :label="activeTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      :title="'修改'+activeTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClose"
    >
      <el-form label-width="100px" :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item :label="activeTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as goods from '../../api/goods'
export default {
  data () {
    return {
      GoodsCateList: [],
      cateId: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      activeName: 'many',
      manyList: [],
      onlyList: [],
      addDialogVisible: false,
      addForm: {
        attr_name: '',
        attr_sel: 'many'
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      activeTitle: '动态参数',
      editDialogVisible: false,
      editForm: {
        attr_name: '',
        attr_sel: 'many'
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getGoodsCateList()
  },
  computed: {
    // 计算属性，如果用的是箭头函数，提供形参就是我们this
    isDisabled: vm => vm.cateId.length !== 3,
    id: vm => (vm.cateId.length === 3 ? vm.cateId[2] : null)
  },
  methods: {
    async getGoodsCateList () {
      const { data: res } = await goods.getGoodsCateList()
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.GoodsCateList = res.data
    },
    handleParamsChange () {
      this.getParamsList()
    },
    handleTabChange () {
      this.getParamsList()
    },
    async getParamsList () {
      if (this.cateId.length !== 3) {
        this.cateId = []
        this.manyList = []
        this.onlyList = []
        return
      }
      const { data: res } = await goods.getParamsList(this.id, this.activeName)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.replace(/,/g, ' ').split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyList = res.data
        this.activeTitle = '动态参数'
      } else {
        this.onlyList = res.data
        this.activeTitle = '静态属性'
      }
    },
    addClose () {
      this.$refs.addFormRef.resetFields()
    },
    postParams () {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) return
        this.addForm.attr_sel = this.activeName
        console.log(this.addForm)
        const { data: res } = await goods.postParams(this.id, this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsList()
        this.addDialogVisible = false
      })
    },
    async editSearch (attrId) {
      const { data: res } = await goods.getParamsById(
        this.id,
        attrId,
        this.activeName
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editClose () {
      this.$refs.editFormRef.resetFields()
    },
    postEditParams () {
      this.$refs.editFormRef.validate(async validate => {
        if (!validate) return
        this.editForm.attr_sel = this.activeName
        const { data: res } = await goods.postEditParams(
          this.id,
          this.editForm.attr_id,
          this.editForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsList()
        this.editDialogVisible = false
      })
    },
    async delParams (attrId) {
      const result = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result === 'cancel') return this.$message.info('取消删除')
      const { data: res } = await goods.delParams(this.id, attrId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsList()
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length !== 0) {
        var obj = { ...row }
        obj.attr_vals = [...row.attr_vals]
        obj.attr_vals.push(obj.inputValue)
        obj.attr_vals = obj.attr_vals.join(' ')
        const { data: res } = await goods.postEditParams(this.id, row.attr_id, obj)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        row.attr_vals.push(row.inputValue)
        row.inputValue = ''
        row.inputVisible = false
      } else {
        this.$message.warning('值不能为空')
      }
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    async removeTag (row, index) {
      var obj = { ...row }
      obj.attr_vals = [...row.attr_vals]
      obj.attr_vals.splice(index, 1)
      obj.attr_vals = obj.attr_vals.join(' ')
      const { data: res } = await goods.postEditParams(this.id, row.attr_id, obj)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      row.attr_vals.splice(index, 1)
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  margin: 15px 0;
}
.params/deep/.el-form-item__label {
  font-size: 16px;
  color: #000;
}
.el-cascader {
  width: 35%;
}
.params/deep/.el-tag {
  margin: 0 8px 10px 0;
}
.tag_input{
  width: 120px;
}
</style>
